const express = require('express');
const routers = express.Router();

// 1. 导入 mysql 包
const mysql = require('mysql');

// 2. 建立连接,配置相关的参数
let options = {
  host: 'localhost',
  // port: '3306',// 默认是3306
  user: 'root',
  password: '123456',
  database: 'hs_cms_db'
};

// 3. 创建与数据库进行连接的对象
let connection = mysql.createConnection(options);
// 4. 建立连接
connection.connect((err) => {
  if (err) {
    // 连接失败
    console.log(err);
  } else {
    console.log('数据库连接成功');
  }
});


routers.post('/login', function(req, res){
  // 5. SQL查询
  let sql_str = `select * from hs_cms_pm`;
  connection.query(sql_str, (err, result, fields) => {
    if (err) {
      console.log('查询失败');
    } else {
      console.log(result);
      // console.log(fields);
      for (const index in result) {
        console.log(result[index].uid);
      }
      console.log(JSON.stringify(result));
      res.send({msg: "登录成功", result: result});
    }
  })


  // res.send({msg: "登录成功"});
});


// 7 带条件查询
routers.post('/login2', (req, res) => {
  // 8.获取从前端传过来的数据
  console.log(req.body, req.query);
  // 9.查询数据
  let uname = req.body.uname;
  if (uname) {
    // 正则匹配
    // 查数据
    let sql = `select * from hs_cms_pm where uname='${uname}'`;
    connection.query(sql, (err, result) => {
      if (err) {
        console.log('数据库错误');
        console.log(sql);
        res.send({msg: "用户查询失败，请联系xxx", code: 110});
      } else {
        if (result.length === 1) {
          let item = result[0];
          if (item.upd === req.body.upd) {
            res.send({
              msg: '登录成功',
              code: 200,
              data: {
                unickname: item.unickname,
                uhead: '/images/3.jpg'
              }
            });
          } else {
            res.send({
              msg: '用户密码错误，请重新输入',
              code: 201
            });
          }
        } else {
          res.send({
            msg: '用户不存在，请重新输入登录',
            code: 202
          });
        }
      }

    });
  } else {
    res.send({
      msg: '请输入用户名',
      code: 203
    })
  }
  // res.send({msg: "登录成功"});
});



module.exports = routers;

